﻿using BloodApp.Model;
using Microsoft.Identity.Client;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BloodApp.Common
{
    public class DbHelperService
    {
        /// <summary>
        /// 数据库操作单例
        /// </summary>
        public static SqlSugarScope DbContext { get; private set; }

        /// <summary>
        /// 数据库文件名
        /// </summary>
        public const string SqliteFileName = "BloodConfig.db";
        static string dbPath = "";
        /// <summary>
        /// 初始化数据库配置
        /// </summary>
        static DbHelperService()
        {
            dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SqliteFileName);
            var config = new ConnectionConfig()
            {
                DbType = DbType.Sqlite,
                ConnectionString = "DataSource=" + dbPath,
                IsAutoCloseConnection = true,
                LanguageType = LanguageType.Chinese
            };
            DbContext = new SqlSugarScope(config, client =>
            {
                //单例参数配置，所有上下文生效
                client.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Debug.WriteLine($"{DateTime.Now.ToString("G")}\r\n{sql}\r\n{DbContext?.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))}\r\n");
                };
            });
        }

        public static void CreateTable()
        {
            //文件是否存在，备份
            if (File.Exists(dbPath))
            {
                DbContext.CodeFirst.SetStringDefaultLength(30);
                DbContext.DbMaintenance.CreateDatabase();
                DbContext.CodeFirst.BackupTable().InitTables(typeof(T_User), typeof(T_Order));//同个数据库中备份表


                ////备份数据库文件
                //string targetPath = AppDomain.CurrentDomain.BaseDirectory + @"BackUpFiles\";
                //string fileName = $@"BloodConfig_{DateTime.Now.ToString("yyyyMMdd")}.db";
                //string targetfile = targetPath + fileName;
                //if (!Directory.Exists(targetPath))
                //{
                //    Directory.CreateDirectory(targetPath);
                //}
                //File.Copy(dbPath, targetfile, true);
            }
            else
            {
                DbContext.CodeFirst.SetStringDefaultLength(30);
                DbContext.DbMaintenance.CreateDatabase();
                DbContext.CodeFirst.InitTables(typeof(T_User), typeof(T_Order));
            }
        }
    }
}
